<script setup>
import { onMounted, reactive, ref } from 'vue'
import { getBusinessHallTreeAPI } from '@/services/businessHall'

defineProps({
  /** 页码 */
  page: {
    type: Number,
    default: 1,
  },
  /** 页容量 */
  pageSize: {
    type: Number,
    default: 10,
  },
})
const emit = defineEmits(['init', 'finish', 'reset', 'update:page', 'update:pageSize'])
// 点击搜索按钮
const onFinish = async () => {
  // 重置页码
  emit('update:page', 1)
  // 重新获取数据
  emit('finish', formState)
}

// 表单初始化
onMounted(() => {
  emit('init', formState)
  getTreeData()
})
// 树形机构信息
const treeData = ref([])
const getTreeData = async () => {
  const res = await getBusinessHallTreeAPI()

  // 递归写法处理成组件所需的树形结构
  function mapChildren({ name, id, children }) {
    const item = { label: name, value: id }
    if (children) {
      item.children = children.map(mapChildren)
    }
    return item
  }
  // 保存树形结构数据用于组件展示
  treeData.value = JSON.parse(res.data).map(mapChildren)
}

// 表单数据
const formState = reactive({
  account: '',
  name: '',
  mobile: '',
  agency: '',
})

// 重置表单
const onReset = async () => {
  // 重置页码和页容量
  emit('update:page', 1)
  emit('update:pageSize', 10)
  // 重置表单后，重新获取数据
  console.log(formRef.value)
  await formRef.value.resetFields()
  emit('reset', formState)
}
const formRef = ref()
</script>

<template>
  <a-form
    ref="formRef"
    name="advanced_search"
    class="ant-advanced-search-form"
    :model="formState"
    @finish="onFinish"
    label-align="right"
  >
    <a-row :gutter="24">
      <a-col :span="8">
        <a-form-item label="司机账号" name="account">
          <a-input allow-clear v-model:value="formState.account" placeholder="司机账号"></a-input>
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="司机姓名" name="name">
          <a-input allow-clear v-model:value="formState.name" placeholder="请输入司机姓名">
          </a-input>
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="司机手机号" name="mobile">
          <a-input
            allow-clear
            v-model:value="formState.mobile"
            placeholder="请输入司机手机号"
          ></a-input>
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item name="agency" label="所属机构">
          <a-tree-select
            v-model:value="formState.agency"
            :tree-data="treeData"
            placeholder="请选择所属机构"
            show-search
            allow-clear
            tree-default-expand-all
            tree-node-filter-prop="label"
          />
        </a-form-item>
      </a-col>
      <a-row justify="center">
        <a-space style="align-items: flex-start">
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-button @click="onReset">重置</a-button>
        </a-space>
      </a-row>
    </a-row>
  </a-form>
</template>
